package com.huikeportal.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.huikeportal.controller.common.Lang;
import com.huikeportal.model.BrandAnalysisGraphData;
import com.huikeportal.model.ChangeGcParam;
import com.huikeportal.model.Language;
import com.huikeportal.model.MessageCommon;
import com.huikeportal.model.ReportGraphData;
import com.huikeportal.model.SiteAllInfo;
import com.huikeportal.model.SiteSelectParam;
import com.huikeportal.model.SquareChange;
import com.huikeportal.model.UserInfo;
import com.huikeportal.model.WordBook;
import com.huikeportal.model.common.SqlParameter;
import com.huikeportal.service.BrandAnalysisService;
import com.huikeportal.service.FootfallGlobalService;
import com.huikeportal.service.LoginService;
import com.huikeportal.service.SelectSiteService;
import com.huikeportal.service.TodayIndexesService;

/**
 * @author focus
 *	品牌分析
 */

@Controller
public class BrandAnalysisController {

	@Autowired
	private HttpSession session;

	@Autowired
	private LoginService loginService;
	
	@Autowired
	private BrandAnalysisService brandAnalysisService;
	
	@Autowired
	private TodayIndexesService todayIndexesService;
	
	@Autowired
	private FootfallGlobalService footfallGlobalService;

	@Autowired
	SelectSiteService selectSiteService;
	
	/**初始化品牌分析页面  */
	@RequestMapping("/brandAnalysis")
	public String brandAnalysis( ModelMap model,String gcSiteId,String brandId,HttpServletRequest request,HttpServletResponse response) throws Exception {
		
		String siteId = gcSiteId;
		
		UserInfo userInfo = (UserInfo) session.getAttribute("sessionUserName");
		userInfo = loginService.getUserInfo(userInfo);//得到用户信息
		String userId = userInfo.getUserId();
        //获取当前系统语言
        String sysLang = session.getAttribute("sysLang").toString();
        //查询当前页面id
        SqlParameter sql = new SqlParameter();
        sql.setSysLang(sysLang);
        sql.setString("brandAnalysis");
        Integer menuId = selectSiteService.getMenuId(sql);
        //获取用户权限按钮信息
        List<WordBook> buttonList = loginService.getUserButtonList(sysLang,
                userId, menuId);
        
        String buttonExport = "0";
        for(WordBook wordBook:buttonList){
        	if("导出".equals(wordBook.getDicValue())){
        		buttonExport = "1";
        		break;
        	}
        }
        
        /** 更换广场初始化 **/
		// 更换广场div初始化数据
		ChangeGcParam changeGcParam = new ChangeGcParam();
		changeGcParam.setSelectType("1");
		List<SiteAllInfo> yuanGcList = loginService.getGcSiteList(userInfo);
		SquareChange squareChange = selectSiteService.squareChangeLoad(
				changeGcParam, yuanGcList,yuanGcList);// 获取初始化更换广场信息
		model.addAttribute("squareChange", squareChange);
		model.addAttribute("selectType", changeGcParam.getSelectType());
		model.addAttribute("backPage", "brandAnalysis");
		
		/**如果场所和品牌都不为空。初始化指标权限，和场所权限*/
		if(siteId != null && !"".equals(siteId) && brandId != null && !"".equals(brandId)){
		/** 更换广场初始化 **/
		/**初始化指标权限*/
        List<String> siteTypes = new ArrayList<String>();
        siteTypes.add("brand");
        /**获取用户指标权限*/
        List<String> userIndexList = footfallGlobalService.getUserIndex(userInfo);
        //数据分析-星期分析model为'2_3'
        String moduleId = FootfallConstant.BRANDCOMP;
        /**指标为场所指标和用户指标交集*/
        //获取趋势分析指标
        List<String> indexList = footfallGlobalService.getIndexListOfModel(userIndexList, moduleId, siteTypes);
        
        //测试数据
        indexList.add("0");
		indexList.add("1");
		indexList.add("2");
		indexList.add("3");
        
        
        //取趋势分析指标分组
        HashMap<String, List<String>> indexListOfGroup = footfallGlobalService.getIndexListOfGroup(indexList);
        model.addAttribute("indexList",JSONObject.fromObject(indexListOfGroup));
        
      //获取排行榜各时间指标
        HashMap<String, Object> dateIndexMap = new HashMap<String, Object>();
        List<String> indexHour  = footfallGlobalService.getTimeIndex("hour");
        dateIndexMap.put("indexHour", indexHour);
        List<String> indexDay  = footfallGlobalService.getTimeIndex("day");
        dateIndexMap.put("indexDay", indexDay);
        List<String> indexWeek  = footfallGlobalService.getTimeIndex("week");
        dateIndexMap.put("indexWeek", indexWeek);
        List<String> indexMonth  = footfallGlobalService.getTimeIndex("month");
        dateIndexMap.put("indexMonth", indexMonth);
        List<String> indexYear  = footfallGlobalService.getTimeIndex("year");
        dateIndexMap.put("indexYear", indexYear);
        model.addAttribute("dateIndexMap",JSONObject.fromObject(dateIndexMap));

        HashMap<String, String>  indexGroupInfo = footfallGlobalService.getIndexGroupInfo();
        model.addAttribute("indexGroupInfo",JSONObject.fromObject(indexGroupInfo));
        HashMap<String, String>  indexInfo = footfallGlobalService.getIndexInfo();
        model.addAttribute("indexInfo",JSONObject.fromObject(indexInfo));
        /**初始化全局分析的指标权限结束*/
		}
		MessageCommon messageCommon = brandAnalysisService.hasSquareAuthor(userInfo);
		if (messageCommon.isFlag()) {
			model.addAttribute("message", messageCommon.getMessage());
			return "noBrandAnalysisAuthor";
		}
		model.addAttribute("buttonExport",buttonExport);
		Language lang = Lang.getInfo(sysLang);
		model.addAttribute("lang",lang);
		model.addAttribute("datetime", footfallGlobalService.getDate());
		String menuHtml = loginService.getMenuHtml(userInfo, "brandAnalysis");//设置左侧列表菜单
		model.addAttribute("menuHtml", menuHtml);// 左侧菜单html
		model.addAttribute("siteId",siteId);
		model.addAttribute("brandId",brandId);
		return "brandAnalysis";
	}
	
	
	
	
	/**前台获取图表数据  */
	@RequestMapping("/getBrandName")
	@ResponseBody
	public List<HashMap<String , String>> getBrandName(HttpServletRequest request,HttpServletResponse response) throws Exception {
		List<HashMap<String , String>> resultList=new ArrayList<HashMap<String,String>>();
		//图表的开始时间
		String brandId=request.getParameter("brandId");//获取几天的数据
		if(brandId.startsWith(",")){
			brandId=brandId.substring(1);
		}
		String[] brandIds =brandId.split(",");
		for(int n=0;n<brandIds.length;n++){
		HashMap<String , String> temMap=new HashMap<String, String>();
		String brand=brandIds[n];
		String brandName=brandAnalysisService.getSiteName(brandIds[n]);
		temMap.put("siteId", brand);
		temMap.put("siteName", brandName);
		resultList.add(temMap);
		
		}
		return resultList;
		
	}
	
	/**前台获取排行榜图表数据  */
	@RequestMapping("/getPaihangGraphData")
	@ResponseBody
	public HashMap<String,Object> getPaihangGraphData(HttpServletRequest request,HttpServletResponse response) throws Exception {
		
		UserInfo userInfo = (UserInfo) session.getAttribute("sessionUserName");
		userInfo = loginService.getUserInfo(userInfo);//得到用户信息
		String type= request.getParameter("type").toString();//获取type类型 1是"客流";2是 "销售额";3是 "提袋率";4是 "客单价";5是 "人效";6 "坪效";7 "集客力";其他 "平均滞留时间";
		String days= request.getParameter("span").toString();//获取时间及其类型
		String[] Strings =days.split("_");
		//日周月年
		String timeType_table=Strings[0];
		//类型，7、14、30天；4、8、12周；3、6、12月；3、5年
		String timeType=Strings[1];
		//图表的开始时间
		String startDate=request.getParameter("from").toString();//获取几天的数据
		//如表的结束时间
		String endDate=request.getParameter("to").toString();//获取几天的数据
		//取场所
		String siteId = request.getParameter("siteId");//获取几天的数据
		//查询图表
		HashMap<String , Object> paraMap=new HashMap<String, Object>();
		paraMap.put("timeType", timeType);
		paraMap.put("timeType_table", timeType_table);//日周月年表
		paraMap.put("startDate", startDate);
		paraMap.put("endDate", endDate);
		paraMap.put("type", type);
		paraMap.put("siteId", siteId);
		paraMap.put("userInfo", userInfo);
		HashMap<String, Object> dataList = brandAnalysisService.getPaihangGraphData(paraMap);
		return dataList;
	}
	
	/**前台获取图表数据  */
	@RequestMapping("/getScatterGraphData")
	@ResponseBody
	public HashMap<String , Object> getScatterGraphData(HttpServletRequest request,HttpServletResponse response) throws Exception {
		
		UserInfo userInfo = (UserInfo) session.getAttribute("sessionUserName");
		userInfo = loginService.getUserInfo(userInfo);//得到用户信息
		String type= request.getParameter("type").toString();//获取type类型 1是"客流";2是 "销售额";3是 "提袋率";4是 "客单价";5是 "人效";6 "坪效";7 "集客力";其他 "平均滞留时间";
		String days= request.getParameter("span").toString();//获取时间及其类型
		String[] Strings =days.split("_");
		//日周月年
		String timeType_table=Strings[0];
		//类型，7、14、30天；4、8、12周；3、6、12月；3、5年
		String timeType=Strings[1];
		//图表的开始时间
		String startDate=request.getParameter("from").toString();//获取几天的数据
		//如表的结束时间
		String endDate=request.getParameter("to").toString();//获取几天的数据
		//取品牌
		String brandId = request.getParameter("brandId");//获取几天的数据
		//取场所
		String siteId = request.getParameter("siteId");//获取几天的数据
		
		HashMap<String , Object> paraMapResult=new HashMap<String, Object>();
		//查询图表
		HashMap<String , Object> paraMap=new HashMap<String, Object>();
		paraMap.put("timeType", timeType);
		paraMap.put("timeType_table", timeType_table);//日周月年表
		paraMap.put("startDate", startDate);
		paraMap.put("endDate", endDate);
		paraMap.put("type", type);
		paraMap.put("brandId", brandId);
		paraMap.put("siteId", siteId);
		paraMap.put("userInfo", userInfo);
		List<HashMap<String, Object>> dataList = brandAnalysisService.getScatterGraphData(paraMap);
		paraMapResult.put("result", dataList);
		return paraMapResult;
	}
	
	
	/**前台获取图表数据  */
	@RequestMapping("/getBrandAnalysis")
	@ResponseBody
	public HashMap<String , Object> getGraphData(HttpServletRequest request,HttpServletResponse response) throws Exception {
		
		UserInfo userInfo = (UserInfo) session.getAttribute("sessionUserName");
		userInfo = loginService.getUserInfo(userInfo);//得到用户信息
		String type= request.getParameter("type").toString();//获取type类型 1是"客流";2是 "销售额";3是 "提袋率";4是 "客单价";5是 "人效";6 "坪效";7 "集客力";其他 "平均滞留时间";
		String days= request.getParameter("span").toString();//获取时间及其类型
		String[] Strings =days.split("_");
		//日周月年
		String timeType_table=Strings[0];
		//类型，7、14、30天；4、8、12周；3、6、12月；3、5年
		String timeType=Strings[1];
		//图表的开始时间
		String startDate=request.getParameter("from").toString();//获取几天的数据
		//如表的结束时间
		String endDate=request.getParameter("to").toString();//获取几天的数据
		//取品牌
		String brandId = request.getParameter("brandId");//获取几天的数据
		//取场所
		String siteId = request.getParameter("siteId");//获取几天的数据
		
		HashMap<String , Object> paraMapResult=new HashMap<String, Object>();
		//查询图表
		HashMap<String , Object> paraMap=new HashMap<String, Object>();
		paraMap.put("timeType", timeType);
		paraMap.put("timeType_table", timeType_table);//日周月年表
		paraMap.put("startDate", startDate);
		paraMap.put("endDate", endDate);
		paraMap.put("type", type);
		paraMap.put("brandId", brandId);
		paraMap.put("siteId", siteId);
		paraMap.put("userInfo", userInfo);
		
		List<HashMap<String, Object>> dataList = brandAnalysisService.getGraphData(paraMap);
	//	List<ReportGraphData> list= brandAnalysisService.getGraphData(paraMap);
		
		String siteIdForJituan = "";
		String siteIdstr = "";
		if(siteId != null && !"".equals(siteId)){
			String[] siteIdarr = siteId.split(",");
			siteIdForJituan = siteIdarr[0];
			for(String siteIdq:siteIdarr){
				siteIdstr = siteIdstr +footfallGlobalService.getSiteName(siteIdq) +"&";
			}
			siteIdstr = siteIdstr.substring(0, siteIdstr.length()-1);
		}
		paraMapResult.put("siteIdstr",siteIdstr);
		
		
		List<String> siteList = new ArrayList<String>();
		footfallGlobalService.getHighSiteId(siteList,siteIdForJituan);
		
		paraMapResult.put("siteIdForJituan",footfallGlobalService.getSiteName(siteList.size()>0?siteList.get(siteList.size()-1):""));
		//插入数据日期类型，日周年月
		paraMapResult.put("timeType_table",timeType_table);
		//插入折线数据
		paraMapResult.put("result", dataList);
		
		
		//获取表格数据
		StringBuffer loadTable=getGlobalTable(dataList,timeType_table,type);
		//放入表格数据
		paraMapResult.put("loadTable", loadTable);
		
		return paraMapResult;
	}
	
	
	/**前台获取图表数据 */
	public StringBuffer getGlobalTable(List<HashMap<String, Object>> dataList,String timeType_table,String type) throws Exception {
		SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd");
		StringBuffer stringTable=new StringBuffer();
		String index =  footfallGlobalService.getOrderField(type);
		
		//计算table列宽
		int rowNum = 3+dataList.size();
		float rowWidth = (float) ((100-5.4)/(rowNum));;
		stringTable.append("<table class='indextable xyliebiao widthall'>");
		stringTable.append("<tr><th class='xykongbai'></th>"
								+"<th class='xyxuhao'>编号</th>"
								+"<th  style='width: "+rowWidth+"%;'>日期</th>"
								+"<th  style='width: "+rowWidth+"%;'>星期</th>");
		List<String> listDate = new ArrayList<String>();
		for(HashMap<String, Object> brandData:dataList){
			stringTable.append("<th style='width: " + rowWidth +"%;'>"+brandData.get("brandName")+"</th>");
			 listDate = (List<String>) brandData.get("listDate");
		}
		stringTable.append("<th class='xykongbai'></th></tr>");
		
		 for (int i = 0; i < listDate.size(); i++){
			String tdxingqi = "";
			String tdriqi = "";
			Calendar cl=Calendar.getInstance();
			cl.setTime(sf.parse(listDate.get(i)));
			int weekInt=cl.get(Calendar.DAY_OF_WEEK);
			tdxingqi = "<td>"+footfallGlobalService.getChinaWeek(weekInt)+"</td>";
			tdriqi = "<td>"+listDate.get(i)+"</td>";
			stringTable.append("<tr>");
			stringTable.append("<td class='xykongbai'></td>"
					+"<td class='xyxuhao'>"+(i + 1)+"</td>");
			stringTable.append(tdriqi);
			stringTable.append(tdxingqi);
			for(HashMap<String, Object> brandData:dataList){
				Object modle = ((List<BrandAnalysisGraphData>)brandData.get("dataList")).get(i);
				String tabledata = footfallGlobalService.getIndexData(modle,index);
				stringTable.append("<td>"+footfallGlobalService.fmtMicrometer(tabledata)+"</td>");
			}
			stringTable.append("<td></td>"); 
			stringTable.append("</tr>");
         }
		 stringTable.append("</table>");
		 
		 return stringTable;
		
/**
		Set<String> dateSet = new HashSet<String>();
		stringTable.append("<table  class='indextable xyliebiao widthall' id=\"tableOut\">");
		stringTable.append("<tr><th class='xykongbai'></th><th class='xyxuhao'>序列</th><th>日期</th><th>星期</th>");
		for(Entry<String, List<BrandAnalysisGraphData>> entry : dataMap.entrySet()){	
			stringTable.append("<th>"+entry.getKey()+"</th>");
			List<BrandAnalysisGraphData> list = entry.getValue();
			for(int i=0,len=list.size();i<len;i++){
				dateSet.add(list.get(i).getDatatime());
			}
		}
		stringTable.append("<th class='xykongbai'></th></tr>");
		
		List<String> dateList = new ArrayList<String>();
		for(String key : dateSet){
			dateList.add(key);
		}
		
		for(int i=0,len=dateList.size();i<len;i++){
			String date = dateList.get(i);
			
			stringTable.append("<tr><td class='xykongbai'></td>");
			 
			stringTable.append("<td class='xyxuhao'>"); 
			stringTable.append((i + 1)); 
			stringTable.append("</td>");
			
			stringTable.append("<td>"); 
			stringTable.append(date); 
			stringTable.append("</td>");
			
			Calendar cl=Calendar.getInstance();
			cl.setTime(sf.parse(date));
			int weekInt=cl.get(Calendar.DAY_OF_WEEK);
			String weekStr="星期一";
			switch (weekInt) {
			case 1:
				weekStr="星期日";
				break;
			case 2:
				weekStr="星期一";
				break;
			case 3:
				weekStr="星期二";
				break;
			case 4:
				weekStr="星期三";
				break;
			case 5:
				weekStr="星期四";
				break;
			case 6:
				weekStr="星期五";
				break;
			case 7:
				weekStr="星期六";
				break;
			default:
				break;
			}
			stringTable.append("<td>"); 
			stringTable.append(weekStr); 
			stringTable.append("</td>");
			
			for(Entry<String,List<BrandAnalysisGraphData>> entry : dataMap.entrySet()){
				List<BrandAnalysisGraphData> tempList = entry.getValue();
				for(int j=0;j<tempList.size();j++){
					BrandAnalysisGraphData temp = tempList.get(j);
					if(temp.getDatatime().endsWith(date)){
						stringTable.append("<td>"); 
						stringTable.append(temp.getInnum()); 
						stringTable.append("</td>");
					}
				}
			}
			
			stringTable.append("<td></td></tr>");
			
		}
		 stringTable.append("</table>");
	*/
		
		
	}
	
	/**前台获取排行榜数据  */
	@RequestMapping("/getBrandRanking")	
	@ResponseBody
	public HashMap<String , Object> getGlobalRanking(HttpServletRequest request,HttpServletResponse response) throws Exception {
		
		
		//场所
		String siteId= request.getParameter("siteId");
		UserInfo userInfo = (UserInfo) session.getAttribute("sessionUserName");
		userInfo = loginService.getUserInfo(userInfo);//得到用户信息
		int type= Integer.parseInt(request.getParameter("type"));
		String from= request.getParameter("from").toString();
		String to= request.getParameter("to").toString();
		String span= request.getParameter("span").toString();
		String days= request.getParameter("span").toString();//获取时间及其类型
		String[] Strings =days.split("_");
		//日周月年
		String timeType_table=Strings[0];
		//类型，7、14、30天；4、8、12周；3、6、12月；3、5年
		String timeType=Strings[1];
		
		
		HashMap<String , Object> paraMap=new HashMap<String, Object>();
		paraMap.put("startDate", from);
		paraMap.put("endDate", to);
		paraMap.put("siteId", siteId);
		paraMap.put("type", type);
		paraMap.put("span", span);
		paraMap.put("timeType_table", timeType_table);
		paraMap.put("timeType", timeType);
		paraMap.put("userInfo", userInfo);
		StringBuffer stringRank=brandAnalysisService.getRanking(paraMap);
		
		paraMap.put("result", stringRank);
		return paraMap;
	}
	
	/**前台获取排行榜数据  */
	@RequestMapping("/getSelectedBrandRanking")	
	@ResponseBody
	public HashMap<String , Object> getSelectedBrandRanking(HttpServletRequest request,HttpServletResponse response) throws Exception {
		
		//场所
		String siteId= request.getParameter("siteId");
		UserInfo userInfo = (UserInfo) session.getAttribute("sessionUserName");
		userInfo = loginService.getUserInfo(userInfo);//得到用户信息
		int type= Integer.parseInt(request.getParameter("type"));
		String from= request.getParameter("from").toString();
		String to= request.getParameter("to").toString();
		String span= request.getParameter("span").toString();
		String days= request.getParameter("span").toString();//获取时间及其类型
		String[] Strings =days.split("_");
		String brandId = request.getParameter("brandId");//获取几天的数据
		//日周月年
		String timeType_table=Strings[0];
		//类型，7、14、30天；4、8、12周；3、6、12月；3、5年
		String timeType=Strings[1];
		
		Language lang=Lang.getInfo("zh_cn");
		HashMap<String , Object> paraMap=new HashMap<String, Object>();
		paraMap.put("startDate", from);
		paraMap.put("endDate", to);
		paraMap.put("siteId", siteId);
		paraMap.put("type", type);
		paraMap.put("span", span);
		paraMap.put("timeType_table", timeType_table);
		paraMap.put("timeType", timeType);
		paraMap.put("userInfo", userInfo);
		paraMap.put("brandId",brandId);
		StringBuffer stringRank=brandAnalysisService.getSelectedRanking(paraMap);
		
		paraMap.put("result", stringRank);
		return paraMap;
	}
	
	
}
